package com.tensquare.user.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;


/**
 * 控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private JwtUtil jwtUtil;

	/**
	 * 更新粉丝数和关注数
	 */
	@RequestMapping(value="/{userid}/{friendid}/{x}",method= RequestMethod.PUT)
	public void updateFanscountAndFollowcount(@PathVariable String userid,@PathVariable String friendid,@PathVariable int x){
		userService.updateFanscountAndFollowcount(userid,friendid,x);
	}

	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	

	
	/**
	 * 修改
	 * @param user
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.PUT)
	public Result update(@RequestBody User user, @PathVariable String id ){
		user.setId(id);
		userService.update(user);		
		return new Result(true,StatusCode.OK,"修改成功");
	}
	
	/**
	 * 删除 必须登录(tokem有效),必须有管理员角色才能删除
	 * @param id
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id,HttpServletRequest request ){
        Claims claims = (Claims) request.getAttribute("admin_claims");
        if (claims != null){
            userService.deleteById(id);
             return new Result(true,StatusCode.OK,"删除成功");
        }
        return new Result(false,StatusCode.ACCESSS_ERROR,"无权限操作");
//		String header = request.getHeader("Authorization");
//		//判断请求头是否有数据,是不是姨约定Bearer开头
//		if (StringUtils.isNotBlank(header) && header.startsWith("Bearer ")) {
//			String token = header.substring(7);
//            Claims claims = jwtUtil.parseToken(token);
//            if (claims != null) {
//                String role = (String) claims.get("role");
//                if ("admin".equals(role) ) {
//                    userService.deleteById(id);
//                    return new Result(true,StatusCode.OK,"删除成功");
//                }
//
//            }
//        }
//        return new Result(false,StatusCode.ACCESSS_ERROR,"无权限操作");
	}

	/**
	 * g给用户发送短信验证码
	 * @param mobile
	 * @return
	 */
	@PostMapping("/sendsms/{mobile}")
	public Result sendsms(@PathVariable String mobile){
		//向rabbit写消息(手机号,验证码,阿里云短信code)
        String checkCode = RandomStringUtils.randomNumeric(4);
        System.out.println("验证码为:"+checkCode);
        redisTemplate.opsForValue().set(mobile,checkCode,5, TimeUnit.MINUTES);
        Map<String,Object> map = new HashMap<>();
        map.put("mobile",mobile);
        //map.put("checkCode",checkCode);
        map.put("temppaltecode","SMS_145592813");//短信模板编号决定着发送短信的内容
		//封装短信模板
		Map<String,String>paramMap = new HashMap<>();
		paramMap.put("code",checkCode);
		map.put("paramMap",paramMap);
        //因为只有一个消费者,只需要采用直接模式即可(路由routingKey跟队列名称一致)
		rabbitTemplate.convertAndSend("itcast-queue-sms",map);
		return new Result(true,StatusCode.OK,"发送成功");
	}
	@PostMapping("/login")
	public Result login(@RequestBody User user){
        User loginUser = userService.login(user.getMobile(),user.getPassword());
		if (loginUser != null){
            //生成token,返回
            String token = jwtUtil.createToken(loginUser.getId(), loginUser.getNickname(), "user");
            Map<String, String> map = new HashMap<>();
            map.put("token",token);
            map.put("name",loginUser.getNickname());
			map.put("id",loginUser.getId());
            return new Result(true,StatusCode.OK,"登陆成功",map);
		}
		return new Result(false,StatusCode.LOGIN_ERROR,"登陆失败");
	}
    /**
     * 增加
     * @param user
     */
    @RequestMapping(method=RequestMethod.POST,value="/register/{code}")
    public Result register(@RequestBody User user, @PathVariable String code ){

        userService.register(user,code);
        return new Result(true,StatusCode.OK,"注册成功");
    }
}
